package lumingweihua.future.cn.lumingweihua.ui.mine;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.zhusx.core.interfaces.IHttpResult;
import com.zhusx.core.network.HttpRequest;
import com.zhusx.core.utils._Bitmaps;
import com.zhusx.core.utils._Densitys;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Hashtable;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.tencent.qzone.QZone;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;
import lumingweihua.future.cn.lumingweihua.R;
import lumingweihua.future.cn.lumingweihua.network.LoadData;
import lumingweihua.future.cn.lumingweihua.network.SimpleHttpListener;
import lumingweihua.future.cn.lumingweihua.ui.BaseCompatActivity;
import lumingweihua.future.cn.lumingweihua.ui.mine.domain.ShareData;

/**
 * todo 邀请好友
 * Author       zhusx
 * Created      2018/3/16 10:54
 */

public class InviteFriendActivity extends BaseCompatActivity {
    @BindView(R.id.iv_qcode)
    ImageView imageView;
    LoadData<ShareData> loadData;
    ShareData en;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_invite_friend);
        ButterKnife.bind(this);
        loadData = new LoadData<>(LoadData.Api.app分享, this);
        loadData._setOnLoadingListener(new SimpleHttpListener<ShareData>() {
            @Override
            public void onLoadComplete(LoadData.Api api, HttpRequest<Object> request, IHttpResult<ShareData> t) {
                en = t.getData();
                imageView.setImageBitmap(createQRImage(en.android, _Densitys.dip2px(InviteFriendActivity.this, 200), BarcodeFormat.QR_CODE, Bitmap.Config.ARGB_8888));
            }
        });
        loadData._loadData();
    }

    @OnClick({R.id.tv_submit})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_submit:
                if (!loadData._hasCache()) {
                    loadData._loadData();
                    return;
                }
                saveBmp2Gallery(_Bitmaps.toBitmap(imageView.getDrawable()), "shareFileName");
                break;
        }
    }

    @OnClick({R.id.tv_qq, R.id.tv_zone})
    public void onShareClick(View view) {
        if (!loadData._hasCache()) {
            loadData._loadData();
            return;
        }
        OnekeyShare oks = new OnekeyShare();
//        oks.disableSSOWhenAuthorize();
        oks.setTitleUrl(en.android);
        oks.setText(en.vice_title);
        oks.setImageUrl(en.img);
        oks.setTitle(en.host_title);
        switch (view.getId()) {
            case R.id.tv_qq:
                oks.setPlatform(QQ.NAME);
                break;
            case R.id.tv_zone:
                oks.setPlatform(QZone.NAME);
                break;
        }
        oks.show(this);
        //showToast("正在唤起,请稍后...");
    }

    @OnClick({R.id.tv_weixin, R.id.tv_quan})
    public void onShareClick2(View view) {
        if (!loadData._hasCache()) {
            loadData._loadData();
            return;
        }
        Platform.ShareParams params = new Platform.ShareParams();
        if (TextUtils.isEmpty(en.android)) {
            params.setShareType(Platform.SHARE_IMAGE);
            params.setImageUrl(en.img);
        } else {
            params.setShareType(Platform.SHARE_WEBPAGE);
            params.setUrl(en.android);
        }
        params.setTitle(en.host_title);
        params.setText(en.vice_title);
        switch (view.getId()) {
            case R.id.tv_weixin:
                ShareSDK.getPlatform(Wechat.NAME).share(params);
                break;
            case R.id.tv_quan:
                ShareSDK.getPlatform(WechatMoments.NAME).share(params);
                break;
        }
        //showToast("正在唤起,请稍后...");
    }

    /**
     * @param bmp     获取的bitmap数据
     * @param picName 自定义的图片名
     */
    public void saveBmp2Gallery(Bitmap bmp, String picName) {
        String fileName = null;
        //系统相册目录
        String galleryPath = Environment.getExternalStorageDirectory()
                + File.separator + Environment.DIRECTORY_DCIM
                + File.separator + "Camera" + File.separator;
        // 声明文件对象
        File file = null;
        // 声明输出流
        FileOutputStream outStream = null;
        try {
            // 如果有目标文件，直接获得文件对象，否则创建一个以filename为名称的文件
            file = new File(galleryPath, picName + ".jpg");
            // 获得文件相对路径
            fileName = file.toString();
            // 获得输出流，如果文件中有内容，追加内容
            outStream = new FileOutputStream(fileName);
            bmp.compress(Bitmap.CompressFormat.JPEG, 90, outStream);
        } catch (Exception e) {
            e.getStackTrace();
        } finally {
            try {
                if (outStream != null) {
                    outStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //通知相册更新
        MediaStore.Images.Media.insertImage(getContentResolver(), bmp, fileName, null);
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        intent.setData(Uri.fromFile(file));
        sendBroadcast(intent);
        showToast("保存成功:" + file.getPath());
    }

    public Bitmap createQRImage(String resourceValue, int QR_WIDTH, BarcodeFormat format, Bitmap.Config config) {
        try {
            int QR_HEIGHT = QR_WIDTH;
            Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            // 图像数据转换，使用了矩阵转换
            BitMatrix bitMatrix = new QRCodeWriter().encode(resourceValue, format, QR_WIDTH, QR_HEIGHT, hints);
            int[] pixels = new int[QR_WIDTH * QR_HEIGHT];
            // 下面这里按照二维码的算法，逐个生成二维码的图片，
            // 两个for循环是图片横列扫描的结果
            for (int y = 0; y < QR_HEIGHT; y++) {
                for (int x = 0; x < QR_WIDTH; x++) {
                    if (bitMatrix.get(x, y)) {
                        pixels[y * QR_WIDTH + x] = 0xff000000;
                    } else {
                        pixels[y * QR_WIDTH + x] = 0xffffffff;
                    }
                }
            }
            // 生成二维码图片的格式，使用ARGB_8888
            Bitmap bitmap = Bitmap.createBitmap(QR_WIDTH, QR_HEIGHT, config);
            bitmap.setPixels(pixels, 0, QR_WIDTH, 0, 0, QR_WIDTH, QR_HEIGHT);
            return bitmap;
        } catch (WriterException e) {
            e.printStackTrace();
        }
        return null;
    }
}
